package com.bjpowernode.threadpool;

import java.util.concurrent.*;

/**
 * ThreadPoolExecutor线程池
 *
 * @author Cat老师，关注我，抖音搜索：java512
 */
public class Test05 {

    public static void main(String[] args) {

        //基于Executor框架实现线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                8,
                16,
                15,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(10),
                Executors.defaultThreadFactory(),
                //Executors.privilegedThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
                //new MyRejectedExecutionHandler()
        );

        for (int i = 0; i < 40000; i++) {
            threadPoolExecutor.execute(new MyRunnable(i));
        }

        threadPoolExecutor.shutdown();
    }

    /**
     * 自定义的拒绝策略
     */
    static class MyRejectedExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //如果任务队列满了，就超时等待，可以设置一个时间
            try {
                executor.getQueue().offer(r, 60, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class MyRunnable implements Runnable {
        private int i;

        public MyRunnable(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + ": " + this.i);
        }
    }
}